package com.sunstar.cwcamerademo

import android.app.Activity
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import android.util.Log

private const val ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION"

class UsbHelper {
    val TAG = "UsbHelper"
    lateinit var manager: android.hardware.usb.UsbManager
    var deviceList = mutableListOf<UsbDevice>()
    var allPermissionHasRequestCallBack: (() -> Unit)? = null

    private val usbReceiver = object : BroadcastReceiver() {
        override fun onReceive(p0: Context?, p1: Intent?) {
            p1?.run {
                if (ACTION_USB_PERMISSION == action) {
                    getParcelableExtra<UsbDevice>(UsbManager.EXTRA_DEVICE)?.let {
                        checkAllPermission()
                    }
                }
            }
        }
    }

    fun checkAllPermission() {
        var hasPermissionNum = 0
        deviceList.forEach { localData ->
            manager.hasPermission(localData).run {
                hasPermissionNum += 1
            }
        }
        if(hasPermissionNum>=deviceList.size){
            allPermissionHasRequestCallBack?.invoke()
        }
    }

    fun unBindActivity(activity: Activity) {
        activity.unregisterReceiver(usbReceiver)
    }

    fun bindActivity(activity: Activity) {
        var filter = IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        activity.registerReceiver(usbReceiver, filter)
    }

    fun getUsbDevice(context: Context): List<UsbDevice> {
        manager =
            context.getSystemService(Context.USB_SERVICE) as android.hardware.usb.UsbManager
        val pendingIntent: PendingIntent =
            PendingIntent.getBroadcast(context, 0, Intent(ACTION_USB_PERMISSION), 0)
        manager.deviceList.forEach {
            deviceList.add(it.value)
            Log.e(TAG, "getUsbDeviceSize: ${deviceList.size}")
            manager.requestPermission(it.value, pendingIntent)
        }
        return listOf()
    }
}